import React from "react";
import { useAuth } from "context/auth-context";
import { Form, Input, Button } from "antd";
import { LoginButton } from "./login";
import { message } from "antd";
import { useAsync } from "utils/index";
const RegisterScreen = ({
  onError,
  onRegister,
}: {
  onError: (error: Error | null) => void;
  onRegister: (isRegister: Boolean) => void;
}) => {
  const { register, user } = useAuth();
  const { run, isLoading } = useAsync(undefined, { thorwOnError: true });
  const handleSubmit = async ({
    cpassword,
    ...values
  }: {
    username: string;
    password: string;
    cpassword: string;
  }) => {
    if (cpassword != values.password) {
      onError({ message: "请确认两次输入的密码是否一致", name: "" });
      return;
    }
    try {
      await run(register(values));
      onError(null);
      onRegister(false);
      message.success("注册成功，请登录页登录");
    } catch (error: any) {
      console.log(error);

      onError(error.message);
      message.error(error.message);
    }
  };
  return (
    <Form onFinish={handleSubmit}>
      <Form.Item
        name={"username"}
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <div>
          {" "}
          <label htmlFor="username">用户名</label>
          <Input placeholder="用户名" type={"text"} id={"username"}></Input>
        </div>
      </Form.Item>
      <Form.Item
        name={"password"}
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <div>
          {" "}
          <label htmlFor="password">密码</label>
          <Input placeholder="密码" type={"password"} id={"password"}></Input>
        </div>
      </Form.Item>
      <Form.Item
        name={"cpassword"}
        rules={[{ required: true, message: "请输入确认密码" }]}
      >
        <div>
          {" "}
          <label htmlFor="cpassword">确认密码</label>
          <Input placeholder="密码" type={"password"} id={"cpassword"}></Input>
        </div>
      </Form.Item>
      <Form.Item>
        {" "}
        <LoginButton htmlType="submit" type={"primary"} loading={isLoading}>
          注册
        </LoginButton>
      </Form.Item>
    </Form>
  );
};

export default RegisterScreen;
